package frame.config;

import frame.pojo.Configuration;
import frame.pojo.MapperStatement;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.util.List;

/**
 * FileName: XMLMapperBuilder
 * Author:   xuan zongjun
 * Date:     2020/11/6 11:58
 * Description: 解析sql的xml
 */


public class XMLMapperBuilder {
    private Configuration configuration;

    public XMLMapperBuilder(Configuration configuration) {
        this.configuration = configuration;
    }

    public void parse(InputStream inputStream) throws DocumentException, ClassNotFoundException {
        Document document = new SAXReader().read( inputStream );
        Element rootElement = document.getRootElement();

        String namespace = rootElement.attributeValue( "namespace" );
        List<Element> select = rootElement.selectNodes( "select" );
        for (Element element : select) {
            String id = element.attributeValue("id");//获取id
            String parameterType = element.attributeValue("parameterType");//输入参数
            String resultType = element.attributeValue( "resultType" );//输出参数




            //statementId
            String key = namespace+"."+id;

            //sql语句
            String textTrim = element.getTextTrim();

            //封装 mappedStatement
            MapperStatement mapperStatement = new MapperStatement();
            mapperStatement.setId( id );
            mapperStatement.setSql( textTrim );
            if(parameterType!=null){
                Class<?> parameterTypeClass = getClassType( parameterType );//返回输入参数的类
                mapperStatement.setParameterType( parameterTypeClass );
            }
            if(resultType!=null){
                Class<?> resultTypeClass = getClassType( resultType );//返回输出参数的类
                mapperStatement.setResultType( resultTypeClass );
            }


            //填充 configuration
            configuration.getMappedStatementMap().put( key,mapperStatement );


        }


    }

    //根据全限定类名，生成类
    private Class<?> getClassType (String parameterType) throws ClassNotFoundException {
            Class<?> aClass = Class.forName(parameterType);
            return aClass;
    }


}
